#!/usr/bin/python
# -*- coding: utf-8 -*-
# vim: ts=4 sw=4 et ai ft=python nowrap

import os
from Tkinter import *
import time
import shutil
import fileinput
import string


def make_changes(fname, source, value):
    for line in fileinput.input(fname, inplace=1):
        line = string.replace(line, source, value)
        print line, 


def run(proxy=None):
    root = Tk()
    root.title('Scheduler')
    Label(root, text='Scheduler', relief=FLAT, justify=CENTER).grid(row=
            0, column=0, columnspan=2)
    user = Label(root, text='UserName:')
    user.grid(row=2, column=0)
    vuser = Entry(root, width=20)
    vuser.grid(row=2, column=1)
    pwd = Label(root, text='Password:')
    pwd.grid(row=3, column=0)
    vpass = Entry(root, width=20, show='*')
    vpass.grid(row=3, column=1)
    shutil.copyfile(os.getcwd() + os.sep + 'setdesktopwallpaper.py', os.getcwd() + 
                    os.sep + 'scheduled.py')
    print proxy
    if proxy:
        make_changes(os.getcwd() + os.sep + 'scheduled.py', 
                     "proxy['IP']", '"' + proxy['IP'] + '"')
        make_changes(os.getcwd() + os.sep + 'scheduled.py', 
                     "proxy['USER']", '"' + proxy['USER'] + '"')
        make_changes(os.getcwd() + os.sep + 'scheduled.py', 
                     "proxy['PASSWORD']", '"' + proxy['PASSWORD'] + '"')
        make_changes(os.getcwd() + os.sep + 'scheduled.py', 
                     "proxy['PORT']", '"' + proxy['PORT'] + '"')

    def execute(event):
        if os.name == 'nt':
            next = time.localtime(time.time() + 60.0)
            cmd2exe = 'schtasks /Create /RU ' + vuser.get() + ' /RP ' + \
                vpass.get() + ' /SC DAILY /TN wallp /TR "pythonw.exe ' + \
                os.getcwd() + os.sep + 'scheduled.py" ' + ' /ST ' + time.strftime('%H:%M:%S', 
                    next)
            os.system(cmd2exe)
        elif os.name == 'posix':
            os.system('crontab -e')
            fhandle = open('cron', 'w')
            cmd2exe = '0 12 * * * python ' + os.getcwd() + os.sep + \
                'scheduled.py'
            fhandle.write(cmd2exe)
            fhandle.close()
        root.destroy()

    schedulebtn = Button(root, text='Schedule it')
    schedulebtn.grid(row=4, column=1)
    schedulebtn.bind('<Button-1>', execute)
    root.wait_window()


if __name__ == '__main__':
    run()
